package com.yuchen.utils.security;

import com.yuchen.utils.RandomUtils;

import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * MD5加密
 * 随机盐
 *
 */
public class PasswordUtils {


	/**
	 * 获得MD5加密密码的方法
	 */
	public static Map genMD5Str(String origString) {
		Map map = new HashMap(2);
		String salt = RandomUtils.randomStr(4);
		map.put("salt",salt);
		String origMD5 = null;
		try {
			origMD5 = md5(origString,salt);
			map.put("password",origMD5);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}

	private static String md5(String origString,String salt){
		String origMD5 = null;
		try {
			origString+=salt;//这里可以换一个规则
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			byte[] result = md5.digest(origString.getBytes());
			origMD5 = byteArray2HexStr(result);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return origMD5;
	}

	/**
	 * 处理字节数组得到MD5密码的方法
	 */
	private static String byteArray2HexStr(byte[] bs) {
		StringBuilder sb = new StringBuilder();
		for (byte b : bs) {
			sb.append(byte2HexStr(b));
		}
		return sb.toString();
	}

	/**
	 * 字节标准移位转十六进制方法
	 */
	private static String byte2HexStr(byte b) {
		String hexStr = null;
		int n = b;
		if (n < 0) {
			// 若需要自定义加密,请修改这个移位算法即可
			n = b & 0x7F + 128;
		}
		hexStr = Integer.toHexString(n / 16) + Integer.toHexString(n % 16);
		return hexStr.toUpperCase();
	}



	/**
	 * @origString
	 * @salt 盐
	 * 验证方法
	 */
	public static boolean verifyStr(String origString,String salt, String MD5Code) {
		return md5(origString,salt).equals(MD5Code);
	}


	/**
	 * 提供一个测试的主函数
	 */
	public static void main(String[] args) {
		//System.out.println("123456:" + genMD5Str("123456"));
		System.out.println("verifyStr:" + verifyStr("123456","FeXh", "B5E85B3C80687D57E8B38269B360EFC2"));

	}
}
